package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.Sports;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.SportsMapper;
import com.itheima.service.SportsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/*
    运动库服务层实现类
 */
@Service(interfaceClass = SportsService.class)
@Transactional
public class SportsServiceImpl implements SportsService {

    //注入运动库持久层接口
    @Autowired
    private SportsMapper sportsMapper;

    //文件上传
    public void upload(List<Sports> sportsList) {
        if(sportsList != null && sportsList.size() > 0){
            for (Sports sports : sportsList) {
                //根据运动助记码是否已经进行了运动设置
                long countByCood = sportsMapper.findCountByCood(sports.getCode());
                if (countByCood > 0) {
                    //已经进行了运动设置,执行更新操作
                    sportsMapper.editNumberByCood(sports);
                }else {
                    //没有进行运动设置,执行插入操作
                    sportsMapper.add(sports);
                }
            }
        }
    }


    //添加运动项
    public void add(Sports sports) {
        //调用持久层接口
        sportsMapper.add(sports);
    }


    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();//当前页码
        Integer pageSize = queryPageBean.getPageSize();//每页条目数
        String queryString = queryPageBean.getQueryString();//查询条件
        //调用分页插件方法
        PageHelper.startPage(currentPage,pageSize);
        //调用持久层接口进行条件查询
        Page<Sports> page = sportsMapper.findPage(queryString);
        //返回结果
        return new PageResult(page.getTotal(),page.getResult());
    }


    //编辑窗回显
    public Sports findById(int id) {
        //调用持久层接口
        Sports sports = sportsMapper.findById(id);
        //返回结果
        return sports;
    }


    //编辑
    public void edit(Sports sports) {
       //调用持久层
       sportsMapper.edit(sports);
    }


    //删除
    public void delete(int id) {
        if (sportsMapper.findBySportsId(id) > 0){
            throw new RuntimeException("存在外键约束,删除失败...");
        }
       //调用持久层方法
       sportsMapper.delete(id);
    }


    //健康干预查询运动信息
    public List<Sports> findAllSport() {
        //调用持久层接口
        List<Sports> list = sportsMapper.findAllSport();
        return list;
    }

}
